package org.surelink.radius.console;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户登录错误控制，每小时只能登录错误5次
 * @author wangjuntao
 *
 */
public class LoginControl
{

	private static final Map<String, LoginControl> userMap = new ConcurrentHashMap<String, LoginControl>();
	private static final int ERROR_MAX = 5;
	private static final int TIME_MAX = 60*60*1000;
	
	private AtomicLong last = new AtomicLong(System.currentTimeMillis());
    private AtomicInteger counter = new AtomicInteger(0);
    private int max = ERROR_MAX;
    
    public LoginControl(int max)
    {
        this.max = max;
    }

    public long getLast()
    {
        return last.get();
    }

    public void setLast(long ltime)
    {
        this.last.set(ltime);
    }

    public int getCount()
    {
        return counter.get();
    }
    
    public int getMax()
    {
    	return max;
    }
    
    public int incr()
    {
    	return counter.incrementAndGet();
    }
    
    public boolean isOutOver()
    {
        long ctime = System.currentTimeMillis();
        if(ctime-last.get()> TIME_MAX)
        {
        	last.set(ctime);
            counter.set(0);
        }
        return counter.get()>=max;
    }
    
    public static  LoginControl getLoginControl(String username){
    	if(userMap.get(username)==null)
    		userMap.put(username, new LoginControl(ERROR_MAX));
    	return userMap.get(username);
    }
    
    public static void reset()
    {
    	userMap.clear();
    }
    
    public static void reset(String username)
    {
    	userMap.remove(username);
    }
    
    public static void main(String[] args) throws Exception
    {
    	LoginControl vs = new LoginControl(6);
        
        for (int i = 0; i < 30; i++)
        {
            
            boolean b = vs.isOutOver();
            System.out.println(vs.getCount()+" "+b);
            vs.incr();
            Thread.currentThread().sleep(1000);
        }
    }


}
